import { lazy } from 'react'
import { Navigate, RouteObject, RouterProvider, createHashRouter } from 'react-router-dom'

import DefaultLayout from '@/layout/default'
import AuthGuard from './components/AuthGuard'
import { ErrorRoutes } from './route/ErrorRoutes'
import Home from '@/pages/Home/index'
import { usePermissionsRoute, useUserActions } from '@/store/user'
import CircleLoading from '@/components/loading/CircleLoading'

import { AppRouteObject } from '#/router'

/* 初始路由 */
/* 获取路由 */
/* 加载有权限的路由组件 */
/* 生成标准路由和菜单 */
/* 生成页面元素权限列表 */
/* 动态添加进本地路由 */
/* 登入判断 */
/* 路由hooks */

// const { VITE_APP_HOMEPAGE: HOMEPAGE } = import.meta.env;
// const AuthGuard = lazy(() => import("./components/AuthGuard"));

const LoginRoute: AppRouteObject = {
  path: '/login',
  Component: lazy(() => import('@/pages/Login'))
}
const PAGE_NOT_FOUND_ROUTE: AppRouteObject = {
  path: '*',
  element: <Navigate to='/404' replace />
}

export default function Router() {
  const { setPermissions } = useUserActions()
  const data = usePermissionsRoute()

  if (!data.length) {
    setPermissions()
    return <CircleLoading></CircleLoading>
  }

  const asyncRoutes: AppRouteObject = {
    path: '/',
    element: (
      <AuthGuard>
        <DefaultLayout />
      </AuthGuard>
    ),
    children: [
      // { index: true, element: <Navigate to="/home" replace /> },
      // { path: "/home", element: <Home /> },
      { index: true, element: <Home /> },
      ...data
      // ...routeList
    ]
  }
  console.log('router redner')
  const routes = [LoginRoute, asyncRoutes, ErrorRoutes, PAGE_NOT_FOUND_ROUTE] // 最终路由表
  const router = createHashRouter(routes as unknown as RouteObject[])

  return <RouterProvider router={router} />
}
